<?php

namespace app\index\controller;

use think\Controller;

use app\index\model\Address;
use app\index\model\Order;
use app\index\model\Qrcode;
use app\index\model\Member;
use app\index\model\Ground;
use app\index\model\SendOrder;
use app\index\model\Express;
use think\Validate;

class Person extends Controller
{
    //个人首页
    public function index(){
        $info = Member::get(session('user.id'));
        $this->assign('info', $info);
        $this->assign('award', model('Award')->where('awar_uid', session('user.id'))->where('awar_status', 0)->count());
        return view('person', ['person' => true]);
    }

    //个人寄件订单
    public function myorder(){
        return view('myorder', ['person' => true]);
    }
    public function getOrder(){
        $status = input('param.status', 0);
        $page = request()->get('page', 0);
        if(!$status) $status = '0,2';
        $orders = Order::field('orde_o_code as billcode, orde_code as code, orde_receiver_info as receiver_addr, orde_sender_id,orde_status as status,create_time')
        ->where('orde_uid', session('user.id'))
        ->where('orde_status', 'in', $status)
        ->order('create_time', 'desc')
        ->limit(config('app.page_num') * $page, config('app.page_num'))
        ->with('member')
        ->select();
        return json(['code'=>0, 'msg'=>'success', 'data'=>$orders]);
    }

    // 个人送件订单
    public function mysender(){
        if(request()->isAjax()){
            $s = input('status', 0);
            $page = request()->get('page', 0);
            $status = [];
            if($s == 2){
                $qrorder = Qrcode::field('billcode, kdcode, create_time')
                ->where('uid', session('user.id'))
                ->where('status', 0)
                ->order('create_time', 'desc')
                ->limit(config('app.page_num') * $page, config('app.page_num'))
                ->select();
                $qrorder->append(['code']);
                return json(mesg(0, 'ok', $qrorder));
            }
            if($s){
                $status[] = ['send_status', '=', '2'];
            }else{
                $status[] = ['send_status', 'in', '0,1'];
            }
            $sendorder = SendOrder::field('send_code as billcode, send_addr as addr, sender_id, send_status as status, create_time')
            ->where('send_uid', session('user.id'))
            ->where($status)
            ->order('create_time', 'desc')
            ->limit(config('app.page_num') * $page, config('app.page_num'))
            ->with('sender')
            ->select();
            // dump($sendorder[0]->sender());
            return json(mesg(0, 'ok', $sendorder));
        }

        return view();
    }

    public function getGood($code){
        try {
            SendOrder::where('send_code', $code)->where('send_uid', session('user.id'))
            ->update(['send_status' => 2]);
            return json(mesg(0, 'ok'));
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    // 查看送件信息
    // public function sendorderInfo($code){
    //     $order = SendOrder::field('send_code as code, send_uid, sender_id')->where('send_code', $code)->where('send_status', 1)->find();
    //     $order->append(['user', 'sender']);
    //     return json($order);
    // }

    // 个人信息
    public function personInfo(){
        return view('person-info', ['person' => true]);
    }

    public function headImg(){
        // halt(request()->file('image'));
        $image = \think\Image::open(request()->file('image'));
        // halt($image);
        $src = '/static/userImage/'. getNonceStr(8) .'.png';
        $image->thumb(150,150, \think\Image::THUMB_CENTER)->save(env('root_path'). 'public' . $src);
        Member::where('memb_id', session('user.id'))->update(['memb_headImage' => $src]);
        // if(file_exists(env('root_path'). 'public' . session('user.image'))){
        //     unlink(env('root_path'). 'public' . session('user.image'));
        // }
        session('user.image', $src);
        return json(mesg(1, 'ok', ['src' => $src]));
    }

    // 二维码列表
    public function mycode(){
        return view('mycode', ['index' => true]);
    }
    public function getCode(){
        // $page = input('page', 0);
        $qrcode = Qrcode::field('id, billcode, create_time')
        ->where('uid', session('user.id'))
        ->where('status', 0)
        ->order('id', 'desc')
        // ->limit(config('app.page_num') * $page, config('app.page_num'))
        ->select();
        $qrcode->append(['order_status']);
        return json(mesg(0, 'success', $qrcode));
    }

    //二维码具体信息
    public function showCode(){
        $code = input('codeNum');
        $qrcode = Qrcode::where('billcode', $code)->find();
        $kdcodes = json_decode($qrcode->kdcode);
        $shelves = [];
        foreach($kdcodes as $v) {
            $content = Express::where('billcode', $v)->value('content');
            $shelves[] = substr($content, 0, 8);
        }
        return view('show-code', ['person' => true, 'code'=>$shelves]);
    }
    public function getQrcode(){
        $billcode = input('orderNum');
        $qr = Qrcode::where('billcode', $billcode)
        ->where('uid', session('user.id'))->find();
        if(!empty($qr) && $qr->status == 0){
            $base64 = baseImage($qr->qrcode);
            return json(mesg(0, 'success', $base64));
        }else{
            return json(mesg(-4, '二维码不存在或失效'));
        }
    }
    
    // 物流信息
    public function expressCheck(){
        return view('express-check', ['person' => true]);
    }
    public function getExpress(){
        $code = input('code');
        if(!empty($code)){
            $info = json_decode(\express\AliKdSearch::kdSearch($code));
            if($info->status == '0'){
                return json(mesg(0, $info->msg, $info));
            }else{
                return json(mesg($info->status, $info->msg));
            }
        }
    }

    
    // 地址管理
    public function address(){
        return view('addr-list');
    }
    public function getAddr(){
        $type = input('param.type', 0);
        $adds = Address::field('addr_type,addr_memberID,addr_delete,create_time,update_time', true)->where('addr_memberID', session('user.id'))
        ->where('addr_type', $type)
        // ->limit(config('app.page_num') *)
        ->select();
        return json(['code'=>0, 'msg'=>'success', 'data'=>$adds]);
    }

    //地址编辑
    public function addrEdit(){
        return view('addr-edit');
    }

    public function addrDefault(){
        $id = input('param.addr_id');
        $type = input('param.addr_type');
        $addr = Address::find($id);
        if(!empty($addr)){
            Address::where('addr_memberID', session('user.id'))->where('addr_type', $type)
            ->update(['addr_default' => 0]);
            $addr->addr_default = 1;
            $addr->save();
            return json(['code'=>0, 'msg'=>'success']);
        }

    }

    // 地址存储
    public function addrSave(){
        $id = request()->post('addr_id');
        $address = explode(' ',request()->post('addr'));
        $default = request()->post('default', 1);
        if(empty($id)) {
            $addr = new Address;
            $addr->addr_type = request()->post('add_type');
        }
        else {
            $addr = Address::find($id);
        }
        if($default == 1){
            Address::where('addr_memberID', session('user.id'))->where('addr_type', input('post.add_type'))->update(['addr_default' => 0]);
            $addr->addr_default = $default;
        }
        $addr->addr_name = request()->post('name');
        $addr->addr_phone = request()->post('phone');
        $addr->addr_province = $address[0];
        $addr->addr_city = $address[1];
        $addr->addr_area = $address[2];
        $addr->addr_detail = request()->post('detail_addr');
        $addr->addr_memberID = session('user.id');
        $result = $addr->save();
        if($result > 0)
            return json(['code'=>0, 'msg'=>'保存成功']);
        else
            return json(['code'=>1, 'msg'=>'保存失败']);
    }

    // 地址删除
    public function delAddr(){
        $addrId = request()->post('id');
        if(!empty($addrId)){
            $addr = Address::where('addr_id', $addrId)->where('addr_memberID', session('user.id'))->find();
            $addr->delete();
        }
        return json(['code'=>0, 'msg'=>'删除成功']);
    }

    public function addNewAddr() {
        return view('add-new-addr', ['person' => true]);
    }

    // 更新支付密码
    public function paypwd(){
        if(request()->isAjax()){
            $captcha = input('captcha');
            $param = [
                'memb_pay_pass' => password_hash(input('paycode'), PASSWORD_DEFAULT),
            ];
            if($captcha != session('captcha')){
                return json([
                    'code' => '0',
                    'msg'    => '验证码不正确',
                ]);
            }
            $memb = new Member();
            $res = $memb->updateInfo($param, session('user.id'));
            return json($res);
        }
        return view('', ['person' => true]);
    }
    
    public function account() {
        return view('', ['person' => true]);
    }

    public function updateAccount(){
        $data = input('post.');
        $validate = Validate::make([
            'password'  => 'require',
            'captcha'   => 'require',
            'phone'     => 'require',
        ]);
        if(!$validate->check($data)){
            return json(mesg(1, $validate->getError()));
        }
        $user = new Member();
        $pwd = $user->where('memb_id', session('user.id'))->value('memb_password');
        if(!password_verify($data['password'], $pwd)){
            return json(mesg(-1, '密码不正确'));
        }
        if($data['captcha'] != session('captcha')){
            return json(mesg(-2, '验证码不正确'));
        }
        $res = $user->updateInfo(['memb_phone' => $data['phone']], session('user.id'));
        session('user.phone', $data['phone']);
        session('captcha', null);
        return json($res);
    }

    public function meet(){
        return view();
    }

    public function myphone() {
        return view();
    }

    public function sendText(){
        $text = input('post.text');
        if(strlen($text) > 300 || strlen($text) == 0) {
            return json(mesg(-2, '字数有误'));
        }
        $txt = file_get_contents(env('root_path').'data/minganci.txt');
        // $content = iconv('gb2312', "utf-8", $txt);
        $words = explode(PHP_EOL, $txt);
        $regx = '/'. join('|', $words) .'/i';
        // $badword1 = array_combine($words,array_fill(0,count($words),'**')); 
        // dump($badword1);
        // $text = strtr($text, $badword1);  
        $res = preg_match($regx, $text, $word);
        if($res){
            return json(mesg(-1, '内容包含敏感词汇，发布失败'));
        }
        // halt($str);
        try{
            db('ground')->insert([
                'uid'   => session('user.id'),
                'content'   => $text,
            ]);
            return json(mesg(0, 'ok'));
        } catch(\Exception $e){
            throw $e;
        }
    }

    public function getContent(){
        if(request()->isAjax()){
            $msgs = Ground::order('create_time', 'desc')->with('member')->paginate(10);
            return json($msgs);
        }
    }
}
